package cn.itcast.yb.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.itcast.controller.IpBean;
import cn.itcast.ft.dto.FtGoodsDTO;
import cn.itcast.ft.dto.FtOrderDTO;
import cn.itcast.ft.dto.FtTokenDTO;
import cn.itcast.ft.dto.PageGoodsdDetailDTO;
import cn.itcast.ft.entity.FTToken;
import cn.itcast.utils.DingDingUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@Slf4j
public class YBController {
    private static List<IpBean> list=new ArrayList<>();
    private static List<FTToken> tokenList=new ArrayList<>();
    @RequestMapping("/ybCreateMarket")
    public String createMarket(@RequestParam(value = "num",defaultValue = "10000") Integer num,
                               @RequestParam(value = "salePrice",defaultValue = "29") String salePrice,
                               @RequestParam(value = "goodsId",defaultValue = "24") String goodsId) {
        if(CollectionUtils.isEmpty(list)){
            try{
                IpBean ipBean1 = new IpBean();
                ipBean1.setIpAddress("117.160.250.132");
                ipBean1.setPort(8080);
                list.add(ipBean1);
            }catch (Exception e){
                IpBean ipBean=new IpBean();
                list.add(ipBean);
            }
        }
        if(CollectionUtils.isEmpty(tokenList)){
            addToken();
        }
        for(int i=0;i<num;i++){
            try {
                for(int j=0;j<list.size();j++){
                    for(int z=0;z<tokenList.size();z++){
                        IpBean ipBean=list.get(j);
                        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ipBean.getIpAddress(), ipBean.getPort()));
                        confireMarketOrder(proxy,tokenList.get(z),goodsId,salePrice);
                        Thread.sleep(2000);
                    }

                }
            } catch (Exception e) {
                log.error("#####异常####" + e.getMessage());
            }
        }
        log.info("####FT执行完成#####");
        return null;
    }
    public void confireMarketOrder(Proxy proxy,FTToken token,String goodsId,String salePrice){
        try{
            createMarketOrder(proxy,token,goodsId,salePrice);
        }catch (Exception e){
            log.error("#####获取商品失败####"+e.getMessage()+"###"+token);
        }
    }
    public void createMarketOrder(Proxy proxy,FTToken token,String goodsId,String salePrice) throws InterruptedException {
        FtGoodsDTO goodsDTO=null;
        String result=null;
        FtTokenDTO ftTokenDTO=null;
        JSONObject jsonObject=new JSONObject();
        jsonObject.putOnce("orderBy","");
        jsonObject.putOnce("pageNum","");
        jsonObject.putOnce("categoryId","");
        jsonObject.putOnce("pageSize","");
        try{
            result = HttpRequest.get("https://api.3rdplanet.cn/api/v1.0/product/queryListByCategoryId")
                    .body(jsonObject.toString()).execute().body();
            goodsDTO= JSONUtil.toBean(result,FtGoodsDTO.class);
        }catch (Exception e){
            log.error("##获取商品数据异常###:"+e.getMessage()+"####返回数据：###"+result);
        }
        if(goodsDTO.getCode()==0){
            if(goodsDTO.getResult()!=null && !CollectionUtils.isEmpty(goodsDTO.getResult().getList())){
                List<PageGoodsdDetailDTO> list=goodsDTO.getResult().getList();
                for(PageGoodsdDetailDTO detailDTO:list){
                    if(detailDTO.getStateId()==1 && detailDTO.getConsignmentPrice().compareTo(new BigDecimal(salePrice))<=0){
                        Proxy finalProxy = proxy;
                        ThreadUtil.execAsync(() -> {
                            saveOrder(finalProxy,token,goodsId,detailDTO);
                        });
                        Thread.sleep(1000);
                    }

                }
            }
        }
    }
    public void saveOrder(Proxy proxy,FTToken token,String goodsId,PageGoodsdDetailDTO detailDTO){
        FtOrderDTO responseDTO=null;
        String response=null;
        try{
            String url="https://h5.ftart.vip/api/mall/sk/co?pId="+goodsId+"&sId" +
                    "="+detailDTO.getId()+"&cuId="+detailDTO.getCuId();
            response=
                    HttpRequest.put(url).header("authorization",
                            "bearer "+token.getToken()).execute().body();
            log.info("#####创建订单结果####"+response);
            responseDTO= JSONUtil.toBean(response,FtOrderDTO.class);
            if(responseDTO.getCode()==0){
                DingDingUtils.sendMsg("热浪您有一个新的订单，请赶紧支付");
                log.error("#####创建订单成功####"+response);
            }
        }catch (Exception e){
            log.error("###创建订单失败###:"+e.getMessage()+",goodsId:"+goodsId+":"+detailDTO.toString()+"##返回的参数信息##:"+response+",#######:"+token);
        }

    }
    public void addToken(){
        FTToken token=new FTToken();
        token.setToken("xGxj4S3qxbdaZtEQ6vIGOa7h1OI");
        token.setRefreshToken("jIO8E4gUBHnsm7UG1Cokjmpf-zA");
        token.setTime(Convert.toDate("2023-03-29 17:43:20"));
//        token.setTime(new Date(new Date().getTime() + 20*60*1000));
        tokenList.add(token);
    }

}
